<%--
  Created by IntelliJ IDEA.
  User: teacher
  Date: 2023/11/2
  Time: 16:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>关键字搜索</title>
    <style>
        li{
            list-style: none;
        }
        #d{
            border: 1px solid #0000ff;
            width: 288px;
            border-top: 0px;
            max-height: 200px;
            overflow: auto;
            padding: 3px 5px;
            display: none;
        }
    </style>
    <script>
        function query(){
            let spell = document.getElementById("spell").value;
            let xhr = new XMLHttpRequest();
            let d = document.getElementById("d");

            // 在每次进行查询之前,先清除原来的数据
            d.innerHTML = "";

            // 在每次进行查询之前,判断用户是否输入了数据
            // 如果用户没有输入数据,则不进行查询
            // 且将下方div隐藏
            if(spell == ""){
                d.style.display = "none";
                return;
            }

            xhr.onreadystatechange=function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    let result = xhr.responseText;
                    let datas = eval("("+result+")");
                    console.log(datas)

                    // 如果服务器响应回来的数据是空的,则将下方div也隐藏起来
                    if(datas.length == 0){
                        d.style.display = "none";
                        return;
                    }

                    d.style.display = "block";
                    for(let i = 0; i < datas.length; i++){
                        d.innerHTML = d.innerHTML + "<li>"+datas[i].message+"</li>";
                    }
                }
            };
            xhr.open("get","${pageContext.request.contextPath}/query?spell="+spell);
            xhr.send(null);
        }
    </script>
</head>
<body>
<input id="spell" type="text" style="width: 300px;" onkeyup="query()">
<div id="d">
</div>
</body>
</html>
